//
//  MediaEditTagViewController.m
//  XPhoto
//
//  Created by baboy on 2019/5/7.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "TagSearchViewController.h"
#import <BKKit/DBQueue.h>
#import <BKKit/UIButton+x.h>
#import <BKKit/NSString+x.h>


#define TAG_QUEUE_ID    @"post_tag"
#define VIEW_PADDING    10

@interface TagSearchViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) NSMutableArray *tagButtons;
@property(nonatomic, strong) NSMutableArray *tagWallButtons;
@end

@implementation TagSearchViewController

- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]) {
        _tags = [NSMutableArray array];
        _tagButtons = [NSMutableArray array];
        _maxSelectedCount = 20;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.descLabel.text = [NSString stringWithFormat:NSLocalizedString(@"max_selected_tag_count_format", @"提醒"), self.maxSelectedCount];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"done", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
    
    NSArray *tags = self.tags;
    _tags = [NSMutableArray array];
    for (NSString * tag in tags) {
        [self addTag:tag withOrigin:CGPointZero];
    }
    NSArray<DBQueueItem*> *tagItems = [DBQueue getAllItemsByQueue:TAG_QUEUE_ID];
    DLOG(@"%@", tagItems);
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self layoutSubViews];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self createTagWall];
    [self layoutSubViews];
}
- (void)cancel:(id)button{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)done:(id)button{
    if (self.delegate && [self.delegate respondsToSelector:@selector(tagSearchViewController:didSearchTags:)]) {
        [self.delegate tagSearchViewController:self didSearchTags:self.tags];
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)removeTag:(UIButton*)btn{
    NSUInteger i = [self.tagButtons indexOfObject:btn];
    [self.tagButtons removeObjectAtIndex:i];
    [self.tags removeObjectAtIndex:i];
    [btn removeFromSuperview];
    [self layoutSubViews];
}
- (UIButton *)createButtonWithTitle:(NSString *)title frame:(CGRect)itemFrame{
    UIButton *btn = [[UIButton alloc] initWithFrame:itemFrame];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = THEME_TAG_BTN_TITLE_FONT;
    [btn setTitleColor:THEME_TAG_BTN_TITLE_COLOR forState:UIControlStateNormal];
    btn.backgroundColor = THEME_TAG_BTN_BG_COLOR;
    btn.clipsToBounds = YES;
    btn.layer.cornerRadius = itemFrame.size.height/2;
    btn.layer.borderWidth = 1.0f;
    btn.layer.borderColor = [THEME_TAG_BTN_BORDER_COLOR CGColor];
    return btn;
}
- (BOOL)addTag:(NSString*)tag withOrigin:(CGPoint)origin{
    if(!tag || tag.length==0){
        return NO;
    }
    if (self.tags.count >= self.maxSelectedCount) {
        [BKIndicator showTips:[NSString stringWithFormat:NSLocalizedString(@"max_selected_tag_count_format", @"提醒"), self.maxSelectedCount]
                     duration:2.0f
                   completion:nil];
        return NO;
    }
    for(NSInteger i = 0; i<self.tags.count; i++){
        if ([[self.tags objectAtIndex:i] isEqualToString:tag]) {
            UIButton *btn = [self.tagButtons objectAtIndex:i];
            [UIView animateWithDuration:0.2
                             animations:^{
                                 btn.transform = CGAffineTransformMakeScale(1.2,1.2);
                             }
                             completion:^(BOOL finished) {
                                 btn.transform = CGAffineTransformIdentity;
                             }];
            return NO;
        }
    }
    
    
    CGSize tagSize = [tag sizeWithAttributes:@{NSFontAttributeName:THEME_TAG_BTN_TITLE_FONT}];
    CGRect itemFrame = CGRectMake(0, 0, tagSize.width+20, tagSize.height + 4);
    itemFrame.origin = origin;
    
    UIButton *btn = [self createButtonWithTitle:tag frame:itemFrame];
    btn.tag = self.tags.count;
    [btn addTarget:self action:@selector(removeTag:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.topView addSubview:btn];
    [self.tags addObject:tag];
    [self.tagButtons addObject:btn];
    [self layoutSubViews];
    [DBQueue addQueue:TAG_QUEUE_ID withKey:[tag md5] withData:tag];
    return YES;
}
- (void)layoutSubViews{
    CGFloat topViewHeight = 0;
    
    //topView: 计算topView 高度
    CGFloat topViewPadding = 10;
    CGRect itemFrame = CGRectMake(topViewPadding, topViewPadding, 0, 0);
    for (NSInteger i = 0; i<self.tagButtons.count; i++) {
        UIButton *btn = [self.tagButtons objectAtIndex:i];
        itemFrame.size = btn.frame.size;
        itemFrame.size.width = MIN(self.view.bounds.size.width - 2* topViewPadding, itemFrame.size.width);
        if ((itemFrame.origin.x + itemFrame.size.width) >= self.view.bounds.size.width) {
            itemFrame.origin.y += itemFrame.size.height+5;
            itemFrame.origin.x = topViewPadding;
        }
        [UIView animateWithDuration:0.1 animations:^{
            btn.frame = itemFrame;
        }];
        
        itemFrame.origin.x += itemFrame.size.width+10;
    }
    if (self.tagButtons.count > 0) {
        topViewHeight = itemFrame.origin.y + itemFrame.size.height + topViewPadding;
    }
    //end topView
    self.topViewHeightConstraint.constant = topViewHeight;
    
    //bottomView
    CGFloat bottomViewHeight = self.scrollView.bounds.size.height - topViewHeight - self.textField.superview.bounds.size.height;
    //
    self.bottomViewHeightConstraint.constant = bottomViewHeight;
}
- (BOOL)collisionDetectWithFrame:(CGRect)itemFrame  existsButtons:(NSArray *)buttons{
    for (UIButton *btn in buttons) {
        CGRect interactionFrame = CGRectIntersection(btn.frame, itemFrame);
        if (!CGSizeEqualToSize(interactionFrame.size, CGSizeZero)) {
            return NO;
        }
    }
    return YES;
}
- (CGRect)detectItemFrameWithBounds:(CGRect)bounds existsButtons:(NSArray *)buttons{
    CGFloat itemMargin = 5;
    CGRect itemFrame = bounds;
    for (UIButton *btn in buttons) {
        //横向
        itemFrame.origin = CGPointMake(btn.frame.origin.x + btn.frame.size.width + itemMargin, btn.frame.origin.y);
        if ( (itemFrame.origin.x + itemFrame.size.width + 10) <= self.bottomView.frame.size.width ) {
            BOOL f = [self collisionDetectWithFrame:itemFrame existsButtons:buttons];
            if (f) {
                return itemFrame;
            }
        }
    }
    for (UIButton *btn in buttons) {
        //向下,顶到最左边
        itemFrame.origin = CGPointMake(VIEW_PADDING, btn.frame.origin.y + btn.frame.size.height + itemMargin);
        BOOL f = [self collisionDetectWithFrame:itemFrame existsButtons:buttons];
        if (f) {
            return itemFrame;
        }
        
        //向下
        itemFrame.origin = CGPointMake(btn.frame.origin.x, btn.frame.origin.y + btn.frame.size.height + itemMargin);
        if ( (itemFrame.origin.x + itemFrame.size.width + 10) <= self.bottomView.frame.size.width ) {
            BOOL f = [self collisionDetectWithFrame:itemFrame existsButtons:buttons];
            if (f) {
                return itemFrame;
            }
        }
    }
    return itemFrame;
}

- (IBAction)addTagFromTagWall:(UIButton *)button{
    NSString *s = [button titleForState:UIControlStateNormal];
    CGPoint p = [self.topView convertPoint:button.frame.origin fromView:self.bottomView];
    [self addTag:s withOrigin:p];
}
-(void)createTagWall{
    if (self.tagWallButtons) {
        [self.tagWallButtons makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    NSArray<DBQueueItem *> *items = [DBQueue getAllItemsByQueue:TAG_QUEUE_ID];
    self.bottomView.hidden = items.count == 0;
    self.clearButton.hidden = self.bottomView.hidden;
    if (!items || items.count == 0) {
        return;
    }
    
    NSMutableArray *buttons = [NSMutableArray array];
    CGFloat bottomViewPadding = 10;
    for (DBQueueItem *item in items) {
        NSString *s = item.data;
        CGFloat fontSize = 20.0 - (s.length*12)/16 ;
        fontSize = MAX((NSInteger)fontSize, 12);
        fontSize  += arc4random_uniform(2)*8;
        DLOG(@"%@, %f", s, fontSize);
        UIFont *font = fontSize > 18 ? [UIFont boldSystemFontOfSize:fontSize] : [UIFont systemFontOfSize:fontSize];
        CGSize itemSize = [s sizeWithAttributes:@{NSFontAttributeName:font}];
        CGRect itemFrame = CGRectMake(bottomViewPadding, bottomViewPadding+10, MIN(itemSize.width + 6, self.bottomView.bounds.size.width - 2*bottomViewPadding), itemSize.height+4);
        itemFrame = [self detectItemFrameWithBounds:itemFrame existsButtons:buttons];
        
        UIColor *textColor = [UIColor colorWithRed:MIN( arc4random_uniform(250)/255.0, 0.6f)
                                             green:MIN( arc4random_uniform(250)/255.0, 0.6f)
                                              blue:MIN( arc4random_uniform(250)/255.0, 0.6f)
                                             alpha:1.0f];
        
        UIButton *btn = [[UIButton alloc] initWithFrame:itemFrame];
        btn.titleLabel.font = font;
        btn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        [btn setTitleColor:textColor forState:UIControlStateNormal];
        [btn setTitle:s forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(addTagFromTagWall:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:btn];
        [buttons addObject:btn];
    }
    self.tagWallButtons = buttons;
}

- (IBAction)clearHistory:(id)sender{
    UIAlertController *alertController = [UIAlertController
                                          alertControllerWithTitle:NSLocalizedString(@"delete_alert_title", @"提示")
                                          message:NSLocalizedString(@"delete_tag_alert_msg", @"提示")
                                          preferredStyle:UIAlertControllerStyleAlert];
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"按钮")
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];
    
    UIAlertAction *enterAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"enter", @"按钮")
                                                           style:UIAlertActionStyleDefault
                                                        handler:^(UIAlertAction *action) {

        [DBQueue removeByQueue:TAG_QUEUE_ID];
        [self createTagWall];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:enterAction];
    [self.navigationController presentViewController:alertController animated:YES completion:nil];
}
#pragma UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *tag = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    CGPoint p = [self.topView convertPoint:self.textField.frame.origin fromView:self.textField.superview];
    BOOL f = [self addTag:tag withOrigin:p];
    if (f) {
        textField.text = nil;
    }
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
